<?php
namespace Shop\Model;
use Think\Model;

class ShopTrueOrderModel extends Model {

	protected $tableName = 'shop_true_order';
	protected $_validate = array(
		array('title', '1,255', '订单标题长度不对', 1, 'length'),
		array('user_id','/(^[1-9][0-9]*)([,][1-9][0-9]*)*$/','用户id参数错误',Model::MUST_VALIDATE),
		array('paid_fee','/[0-9]\d*/','支付总价参数错误',Model::MUST_VALIDATE),

	);
	protected $_auto = array(
		array('create_time', NOW_TIME, self::MODEL_INSERT),
		array('status', '1', self::MODEL_INSERT),
	);

	public function true_order_list($option){	//获取列表
		if (!empty($option['user_id'])){
			$where_arr[] = "user_id REGEXP '(^|[^0-9])".$option['user_id']."($|[^0-9])' ";
		}
		if (!empty($option['status'])){
			$where_arr[] = 'status = ' . $option['status'];
		}else{
			$where_arr[] = 'status > 0';
		}
		if (!empty($option['title'])){
			$where_arr[] = "title LIKE '%" . $option['title'] . "%'";
		}
		if (!empty($option['create_time'])){
			$where_arr[] = 'create_time >= ' . $option['create_time'];
		}
		if (!empty($option['ids'])){
			$where_arr[] = 'id in(' . implode(',', $option['ids']) . ')';
		}
		$where_str = '';
		if (!empty($where_arr)){
			$where_str .=  implode(' and ', $where_arr);
		}
		if($option['status'] == 1){
			$order_str = 'warn_time asc';
		}else{
			$order_str = 'create_time desc';
		}
		$ret['list']  = $this->where($where_str)->order($order_str)->page($option['page'], $option['r'])->select();
		$ret['count'] = $this->where($where_str)->count();
		return $ret;
	}

	public function true_order_by_id($id){	//按id获取订单
		$ret = $this->where('id ='.$id)->find();
		return $ret;
	}

	public function edit_true_order($data){		//新增或编辑订单
		if (empty($data['id'])){
			$ret = $this->add($data);
		}else{
			$ret = $this->where('id='.$data['id'])->save($data);
		}
		return $ret;
	}

	public function true_order_status($ids,$status){		//设置订单状态
		if (!is_array($ids)){
			$ids = array($ids);
		}
		return $this->where('id in (' . implode(',', $ids) . ')')->setField('status',$status);
	}

	protected function _after_select(&$ret,$option){
		foreach ($ret as &$ret){
			$ret['address'] =(!empty($ret['address']) ? json_decode($ret['address'],true)  : '');
			$ret['info'] =(!empty($ret['info']) ? json_decode($ret['info'],true)  : '');
		}
	}

	protected function _after_find(&$ret,$option){
		$ret['address'] =(!empty($ret['address']) ? json_decode($ret['address'],true)  : '');
		$ret['info'] =(!empty($ret['info']) ? json_decode($ret['info'],true)  : '');
	}

}

